#!/bin/bash
# Define Color
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m' # No color
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

# 中文的sh
# ########################################################################
# 变量定义
# ########################################################################
ServerPort=80                                                                       # GS端口
PublicIP="111"                                                                      # 公网IP定义
SignalType=""                                                                       # 信号定义
GM_VersionPath="/app/.version"                                                      # GM版本的位置存放
GM_PackageName="gm.tar.gz"                                                          # GM包名
GM_FolderPath="/app/gs"                                                             # GM的目录位置存放
GM_ScriptPath="$GM_FolderPath/bin"                                                  # GM脚本目录位置
GM_ScriptPathName="$GM_ScriptPath/gs_main"                                          # GM脚本位置
GM_CheckURL="https://api.gmssh.com/api/package_v2/package_get"                   # GM的check地址
OS_CpuArch=""                                                                       # 操作系统CPU架构
GM_ServiceUser="root"                                                               # 运行服务的用户
GM_ServiceGroup="root"                                                              # 运行服务的用户组
GM_ServiceLogDir="/app/gs/logs"                                                     # 日志目录
GM_ServiceVersionFile="/app/gs/.version"                                            # GM版本文件位置
GM_ServiceErrorLog="$LOG_DIR/error.log"                                             # 错误日志
GM_ServiceOutputLog="$LOG_DIR/output.log"                                           # 标准输出日志
SERVICE_NAME="GMServer"                                                             # 服务名称
GM_SERVICE_DIR="/etc/systemd/system"                                                # 服务基础目录
GM_SERVICE_FILE="$GM_SERVICE_DIR/$SERVICE_NAME.service"                             # 服务配置文件路径
GM_SERVICE_CONFIG_FILE="$GM_ScriptPath/config.json"                                 # 服务配置文件路径


# ########################################################################
# 系统信息获取
# ########################################################################
detect_distro() {

    # 脚本标题（美化输出）
    echo -e "\n===== 选择操作系统架构 \ Please select the operating system architecture ====="

    # 定义架构选项（键：用户输入，值：标准架构名称）
    declare -A ARCH_MAP=(
        ["1"]="x86_64"
        ["x86"]="x86_64"
        ["2"]="arm"
        ["arm"]="arm"
    )

    # 循环获取有效输入（直到用户输入正确）
    while true; do
        # 显示选项
        echo -e "\nPlease select architecture (enter number or architecture name):"
        echo "  1. x86 Architecture (applicable to mainstream processors such as Intel/AMD)"
        echo "  2. ARM Architecture (applicable to Raspberry Pi, embedded devices, etc.)"
        
        # 读取用户输入（去除首尾空格）
        read -p "Your choice:" USER_INPUT
        USER_INPUT=$(echo "$USER_INPUT" | xargs)  # 处理空输入和空格
        
        # 验证输入是否有效
        if [[ -n "${ARCH_MAP[$USER_INPUT]}" ]]; then
            SELECTED_ARCH="${ARCH_MAP[$USER_INPUT]}"
            break  # 输入有效，退出循环
        else
            # 输入无效，提示重试
            echo -e "\033[31m错误：无效的选择，请输入 1/2 或 x86 \ Error: Invalid selection, please enter 1/2 or x86 /arm\033[0m"  # 红色错误提示
        fi
    done

    # 输出选择结果（绿色高亮）
    echo -e "\n\033[32m✅ Confirmed selection:${SELECTED_ARCH} architecture\033[0m"
    OS_CpuArch=$SELECTED_ARCH
    # OS_CpuArch=$(arch)
    if [ -f /etc/os-release ]; then
        source /etc/os-release
        DISTRO="$NAME"
        DISTRO_VERSION="$VERSION_ID"
    elif [ -f /etc/redhat-release ]; then
        DISTRO=$(awk '{print $1}' /etc/redhat-release)
        DISTRO_VERSION=$(awk '{print $(NF-1)}' /etc/redhat-release)
    else
        DISTRO="Unknown"
        DISTRO_VERSION="0"
    fi
}

get_sysinfo() {
    echo "[+] OS: $DISTRO $DISTRO_VERSION ($OS_NAME)"
    echo "[+] ARCH: $OS_ARCH, CORES: $CPU_CORE_NUM"
}

# ########################################################################
# 基础系统源管理
# ########################################################################
detect_pm() {
    if command -v yum &>/dev/null; then
        PM="yum"
    elif command -v apt-get &>/dev/null; then
        PM="apt-get"
    else
        echo "[-] No supported package manager"
        exit
    fi

    if ((DEBUG == 1)); then
        if [ "$PM" = "yum" ]; then
            yum clean all && yum makecache
        else
            apt-get update -y
        fi
    fi
}

# ########################################################################
# 执行安装GM
# ########################################################################
check_Upgrade() {
    echo "[*] Check if an upgrade is needed"
}


# 交互式询问用户是否需要更新
prompt_update() {
    # 显示提示信息，告知用户可输入的选项
    echo "Is an update required?"
    echo "Please enter (y/yes to confirm, other keys to cancel): "
    
    # 读取用户输入（不显示输入内容长度限制，支持大小写）
    read -r response
    
    # 转换输入为小写，统一判断逻辑
    lower_response=$(echo "$response" | tr '[:upper:]' '[:lower:]')
    
    # 判断用户输入
    if [ "$lower_response" = "y" ] || [ "$lower_response" = "yes" ]; then
        echo "[*] The user confirms the update and starts the update operation..."
        return 0  # 0表示成功/确认
    else
        echo "[-] User cancels update and exits the operation..."
        return 1  # 非0表示取消
    fi
}

install_tar_deps() {
    case "$DISTRO" in
    CentOS* | RedHat*)
        yum install -y tar
        ;;
    Ubuntu* | Debian*)
        apt install -y tar
        ;;
    *)
        echo "[-] Unsupported distro: $DISTRO"
        echo "[-] Please manually install the tar command and try again"
        exit 1
        ;;
    esac
}

uninstall_gm_deps() {
    # 删除文件位置
    rm -rf $GM_FolderPath
}

install_build_deps() {
    check_Upgrade

    echo "[*] CPU Type: $OS_CpuArch"
    if [ -e "$GM_ServiceVersionFile" ]; then
        version=$(cat "$GM_ServiceVersionFile")
        # 注意反斜杠后面不能有任何字符，包括空格
        response=$(curl -s -w "\n%{http_code}" \
        -X POST \
        -H "X-Requested-With: XMLHttpRequest" \
        -H "upload-token: 01841009b01f4f56f032792ceafaef60" \
        -F "cpu=$OS_CpuArch" \
        -F "type=2" \
        -F "version=$version" \
        "$GM_CheckURL")
    else
        response=$(curl -s -w "\n%{http_code}" \
        -X POST \
        -H "X-Requested-With: XMLHttpRequest" \
        -H "upload-token: 01841009b01f4f56f032792ceafaef60" \
        -F "cpu=$OS_CpuArch" \
        -F "type=2" \
        "$GM_CheckURL")
    fi
    # 检查请求是否成功
    if [ -z "$response" ]; then
        echo "[-] The request failed and no response was received"
        exit 1
    fi
    echo ">>> $response"
    # 解析download_url（位于data数组第一个元素的file数组第一个元素中）
    escaped_url=$(echo "$response" | grep -o '"download_url":"[^"]*"' | head -n 1 | sed 's/"download_url":"//;s/"//')
    download_url=$(echo "$escaped_url" | sed 's/\\//g')
    # 解析version（位于data数组第一个元素中）
    gm_Filename=$(echo "$response" | grep -o '"filename":"[^"]*"' | head -n 1 | sed 's/"filename":"//;s/"//')
    version=$(echo "$response" | grep -o '"version":"[^"]*"' | head -n 1 | sed 's/"version":"//;s/"//')
    # 解析update（如果存在该字段，这里假设可能在data数组中或根节点）
    # 注意：您提供的响应中没有update字段，这里是兼容处理
    update=$(echo "$response" | grep -o '"update":[^,}]*' | head -n 1 | sed 's/"update"://;s/ //g')
    # 打印解析结果
    echo "download_url: $download_url"
    echo "version: $version"
    echo "gm_Filename: $gm_Filename"
    update_err_msg="The field was not found"
    echo "update: ${update:-$update_err_msg}"
    if command -v tar &> /dev/null; then
        echo "[+] The tar command is installed"
    else
        install_tar_deps
    fi
    cd $GM_FolderPath
    if [ -e "$GM_ServiceVersionFile" ]; then
        if [ "$update" = "true" ]; then
            echo "[*] Need to update, download address：$download_url"
            if prompt_update; then                                                  # 调用函数并根据返回值执行不同操作
                echo "[*] Update operation in progress..."
                curl -Ss --connect-timeout 5 -m 60 -o $gm_Filename $download_url
                # gm_Filename=$(basename "$dw_url")
            else
                echo "[-] Cancel installation..."
                exit 1
            fi
        else
            echo "[+] The current version is already the latest..."
            exit 0
        fi
    else
        echo "[*] Perform the installation..."
    fi
    cd $GM_FolderPath
    # curl -v --connect-timeout 5 -m 60 -O "$download_url" \
    # -H "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7" \
    # -H "Accept-Language: zh-CN,zh;q=0.9" \
    # -H "Cache-Control: no-cache" \
    # -H "Connection: keep-alive" \
    # -H "Pragma: no-cache" \
    # -H "Upgrade-Insecure-Requests: 1" \
    # -H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36" \
    # --insecure
    curl -Ss --connect-timeout 5 -m 60 -o $gm_Filename $download_url
    # gm_Filename=$(basename "$dw_url")
    tar -xvf $gm_Filename                                                           # tar解压目录
    rm -rf $gm_Filename                                                             # 移除源文件
    check_script
    create_log_dir
    create_service_file
}

create_service_file() {                                                             # 创建systemd服务配置文件
    echo "[-] Creating a Service Profile $GM_SERVICE_FILE..."                       # /etc/systemd/system/myscript.service
    cat > "$GM_SERVICE_FILE" << EOF                                                 # TODO: 使用systemctl管理服务
[Unit]
Description=$SERVICE_NAME Service
After=network.target

[Service]
ExecStart=$GM_ScriptPathName http
User=$GM_ServiceUser
Group=$GM_ServiceGroup
WorkingDirectory=$GM_ScriptPath
Environment="PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
Restart=always
RestartSec=5
StandardOutput=append:$GM_ServiceOutputLog
StandardError=append:$GM_ServiceErrorLog
LimitNOFILE=4096

[Install]
WantedBy=multi-user.target
EOF
    if [ ! -f "$GM_SERVICE_FILE" ]; then                                            # 检查配置文件是否创建成功
        echo "[-] Error: Service profile creation failed"
        exit 1
    fi
    Check_Server_Port
    touch $GM_ServiceErrorLog
    touch $GM_ServiceOutputLog
    systemctl daemon-reload
}


check_script() {
    if [ ! -f "$GM_ScriptPathName" ]; then
        echo "[-] Error: Target script $GM_ScriptPathName does not exist"
        exit 1
    fi

    if [ ! -x "$GM_ScriptPathName" ]; then
        echo "[-] Warning: The target script does not have executable permissions, it will be added..."
        chmod +x "$GM_ScriptPathName" || {
            echo "[-] Error: Unable to add executable permissions to script"
            exit 1
        }
    fi
}

create_log_dir() {
    if [ ! -d "$GM_ServiceLogDir" ]; then
        echo "[*] Create a log directory $GM_ServiceLogDir..."
        mkdir -p "$GM_ServiceLogDir" || {
            echo "[-] Error: Unable to create log directory $GM_ServiceLogDir"
            exit 1
        }
    fi

    # 设置日志目录权限
    echo "[*] Set log directory permissions..."
    chown -R "$GM_ServiceUser:$GM_ServiceGroup" "$GM_ServiceLogDir" || {
        echo "[-] Error: Unable to set log directory permissions"
        exit 1
    }
}

# ########################################################################
# 服务管理
# ########################################################################
start_gm_service() {
    if ! systemctl is-active --quiet "$SERVICE_NAME"; then
        echo "[*] Start $SERVICE_NAME service..."
        systemctl start "$SERVICE_NAME" || {
            echo "[-] Error: Service start failed"
            exit 1
        }
        echo "[+] Service started successfully"
    else
        echo "[+] $SERVICE_NAME Service already running"
    fi
}
# 重启服务
restart_gm_service() {
    echo "[*] Restart $SERVICE_NAME service..."
    systemctl restart "$SERVICE_NAME" || {
        echo "[-] Error: Service restart failed"
        exit 1
    }
    echo "[+] Service restarted successfully"
}

# 查看服务状态
status_gm_service() {
    echo "[*] View $SERVICE_NAME Service Status..."
    systemctl status "$SERVICE_NAME"
}

enable_gm_service() {
    echo "[*] Enable $SERVICE_NAME automatic startup..."
    systemctl enable "$SERVICE_NAME" || {
        echo "[-] Error: Failed to set auto-start"
        exit 1
    }
    echo "[+] The automatic startup setting is successful"
}

# 禁用开机自启
disable_gm_service() {
    echo "[*] Disable $SERVICE_NAME automatic startup..."
    systemctl disable "$SERVICE_NAME" || {
        echo "[-] Error: Failed to cancel the automatic start"
        exit 1
    }
    echo "[*] Automatic startup has been canceled"
}

# 停止服务
stop_gm_service() {
    if systemctl is-active --quiet "$SERVICE_NAME"; then
        echo "[*] Stop $SERVICE_NAME server..."
        systemctl stop "$SERVICE_NAME" || {
            echo "[-] Error: Service stop failed"
            exit 1
        }
        echo "[+] Service stopped successfully"
    else
        echo "[+] $SERVICE_NAME The service is not running"
    fi
}

# 查看日志
view_gm_logs() {
    if [ "$1" = "error" ]; then
        echo "[+] View error logs ($GM_ServiceErrorLog)..."
        tail -f "$GM_ServiceErrorLog"
    else
        echo "[+] View output log ($GM_ServiceOutputLog)..."
        tail -f "$GM_ServiceOutputLog"
    fi
}

# 卸载服务
uninstall_gm_service() {
    stop_gm_service
    disable_gm_service
    
    echo "[*] Deleting a service configuration file..."
    rm -f "$GM_SERVICE_FILE" || {
        echo "[-] Error: Failed to delete service profile"
        exit 1
    }
    
    systemctl daemon-reload
    echo "[+] Service uninstalled"
    # echo "[+] 服务已卸载（日志文件保留在 $GM_ServiceLogDir）"
}
# ########################################################################
# 进程退出管理
# ########################################################################
Process_Exit() {
    case $SignalType in
        SIGINT)
            EXIT_MSG="[-] Capture the Ctrl+C signal to exit"
            ;;
        SIGTERM)
            EXIT_MSG="[-] Capture the process being killed"
            ;;
        SIGHUP)
            EXIT_MSG="[-] Captured terminal connection exception"
            ;;
        *)
            EXIT_MSG="[-] Unknown signal"
            ;;
    esac
    exit 1
}

trap 'SignalType*SIGINT; Process_Exit' SIGINT
trap 'SignalType*SIGTERM; Process_Exit' SIGTERM
trap 'SignalType*SIGHUP; Process_Exit' SIGHUP


# ########################################################################
# GM环境检查
# ########################################################################
Install_ENV_Check(){
    CURL_CHECK=$(which curl)
    if [ "$?" == "0" ];then
        echo "[+] Check curl $?"
    else
        echo "[-] Check whether the curl command is installed in the environment"
        exit 1
    fi
    echo "[*] Environment check: curl is installed  $CURL_CHECK"

    if ! command -v systemctl &> /dev/null; then
        echo "[-] Error: The current system does not support systemd, cannot continue"
        exit 1
    fi
}

# ########################################################################
# 检验当前登录的用户
# ########################################################################
Check_User_Access(){
    echo "[*] Check whether user permissions can be installed normally"
    # TODO: 先暂时不考虑Root用户离线部署
    if [ $(whoami) != "root" ];then
        echo "[-] Installation by non-root users is not currently supported"
    else
        echo "[+] User permissions are normal"
    fi
    # 如果是root用户安装的位置
    # 如果是非root用户安装的位置区别
    # 初始化目录
    declare -a dirs_to_create=(
        # "$INSTALL_LOG_DIR"
        "$GM_FolderPath"
        "$GM_SERVICE_DIR"
    )

    for dir in "${dirs_to_create[@]}"; do
        if [ ! -d "$dir" ]; then
            sudo mkdir -p "$dir"
            sudo chmod 755 "$dir"
        fi
    done
    echo "[+] Directory initialization completed"
}


# ########################################################################
# 读取服务器公网IP
# ########################################################################
Get_Public_IP(){
    echo "Read the server's external IP address"
    PublicIP=$(curl -s icanhazip.com)
    Get_ServerPort
}

Get_ServerPort() {
    if [ -e "$GM_SERVICE_CONFIG_FILE" ]; then
        ServerPort=$(grep "http_port" $GM_SERVICE_CONFIG_FILE | grep -o -P '\d+')
        echo "[+] Port : $ServerPort"
    else
        echo "[-] Configuration file not found, please reinstall..."
        exit 1
    fi
}

Check_Server_Port() {
    Get_ServerPort
    PORT=$ServerPort
    echo "Port number for current service configuration: $PORT"
    echo "Checking if port $PORT is occupied ..."
    echo "----------------------------------------"

    # 检测端口占用（优先使用lsof，兼容Linux和macOS）
    # 若lsof不存在，使用netstat检测（Linux系统）
    if command -v netstat &> /dev/null; then
        RESULT=$(netstat -tuln | grep -F ":$PORT " 2>/dev/null)
        if [ -n "$RESULT" ]; then
            echo "Port $PORT is already occupied, network connection information:"
            echo "$RESULT"
            echo "Tip: Use 'Sudo Netstat - tulnp | grep: $PORT' to view process IDs"
            echo -e "${RED}建议：可以修改端口号后启动服务 \ 
            Suggestion: You can start the service after modifying the port number${NC}"
            echo -e "${RED}建议：使用bash gm.sh setport命令设置端口号 \ 
            Suggestion: Use the bash gm.sh setport command to set the port number...${NC}"
            exit 1
        else
            echo "Port $PORT is not occupied"
        fi
    else
        # 若netstat也不存在，使用ss检测（较新的Linux系统）
        if command -v ss &> /dev/null; then
            RESULT=$(ss -tuln | grep ":$PORT" 2>/dev/null)
            if [ -n "$RESULT" ]; then
                echo "Port $PORT is already occupied, network connection information:"
                echo "$RESULT"
                echo "Tip: Use 'sudo ss tulnp | grep: $PORT' to view process IDs"
                echo -e "${RED}建议：可以修改端口号后启动服务 \ 
                Suggestion: You can start the service after modifying the port number${NC}"
                echo -e "${RED}建议：使用bash gm.sh setport命令设置端口号 \ 
                Suggestion: Use the bash gm.sh setport command to set the port number...${NC}"
                exit 1
            else
                echo "Port $PORT is not occupied"
            fi
        else
            # 若netstat也不存在，使用ss检测（较新的Linux系统）
            if command -v lsof &> /dev/null; then
                # 使用lsof检测，显示占用进程详情
                RESULT=$(lsof -i :$PORT 2>/dev/null)
                if [ -n "$RESULT" ]; then
                    echo "Port $PORT is already occupied, process information is as follows:"
                    echo "$RESULT" | awk 'NR==1 || $1!="COMMAND"'  # 过滤重复的COMMAND行
                    echo -e "${RED}建议：可以修改端口号后启动服务 \ 
                    Suggestion: You can start the service after modifying the port number${NC}"
                    echo -e "${RED}建议：使用bash gm.sh setport命令设置端口号 \ 
                    Suggestion: Use the bash gm.sh setport command to set the port number...${NC}"
                    exit 1
                else
                    echo "Port $PORT is not occupied"
                fi
            else
                echo "Error: Detection tool (lsof/netstat/ss) not found, unable to detect port"
                exit 1
            fi
        fi
    fi

    echo "----------------------------------------"
}

Set_Server_Port() {
    PORT="$1"
    echo "Update server port...${PORT}"
    if [ -e "$GM_SERVICE_CONFIG_FILE" ]; then
        sed -i.bak -E "s/(\"http_port\"\s*:?\s*\"):?[0-9]+?(\")/\1${PORT}\2/" $GM_SERVICE_CONFIG_FILE
    else
        echo "[-] Configuration file not found, please reinstall..."
        exit 1
    fi
    Get_ServerPort
    restart_gm_service
}

# ########################################################################
# 安装结束
# ########################################################################
Install_Done(){
    # check server port
    # GM_SERVICE_CONFIG_FILE
    echo -e "※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※"
    echo -e ""
    echo -e "\033[32mCongratulations! Installed successfully!\033[0m"
    echo -e "" 
    echo -e "※※※※※※※※※※※※※※※※※※※※※※※※GMSSH Info※※※※※※※※※※※※※※※※※※※※※※※※※※※※※"
    echo -e ""
    echo -e "[+][Cloud Server] Please release it in the security group \033[31m$ServerPort\033[0m Port"
    echo -e "[+] \033[33mGM Service access address：http://$PublicIP:$ServerPort\033[0m"
}

# ########################################################################
# GM安装/卸载
# ########################################################################
Install_GM(){
    detect_distro
    Install_ENV_Check
    get_sysinfo
    detect_pm
    Check_User_Access
    install_build_deps
    start_gm_service
    Get_Public_IP
    Install_Done
    show_gm_help
}

Uninstall_GM() {
    get_sysinfo
    uninstall_gm_service
    uninstall_gm_deps
}

# ########################################################################
# 控制面板
# ########################################################################
show_gm_help() {
    # 中英文左右对齐显示（英文左对齐，中文右对齐）
    echo -e "\033[1mHow to use / 使用方法:\033[0m \033[33m$0\033[0m [Command / 命令]"
    echo -e "\033[1mCommand List / 命令列表:\033[0m"
    echo "------------------------------------------------------------------------"
    
    # 使用固定宽度字段确保中文右对齐（总宽度80字符）
    printf "  \033[34minstall\033[0m     - %-40s %s\n" \
        "Install service (create config files, etc.)" \
        "- 安装服务（创建配置文件、日志目录等）"
    
    printf "  \033[34mstart\033[0m       - %-40s %s\n" \
        "Start service" \
        "- 启动服务"
    
    printf "  \033[34mstop\033[0m        - %-40s %s\n" \
        "Stop service" \
        "- 停止服务"

    printf "  \033[34msetport\033[0m     - %-40s %s\n" \
        "Update service port" \
        "- 更新服务端口"

    printf "  \033[34mport\033[0m        - %-40s %s\n" \
        "Get port" \
        "- 获取服务端口号"

    printf "  \033[34mrestart\033[0m     - %-40s %s\n" \
        "Restart service" \
        "- 重启服务"
    
    printf "  \033[34mstatus\033[0m      - %-40s %s\n" \
        "Check service status" \
        "- 查看服务状态"
    
    printf "  \033[34menable\033[0m      - %-40s %s\n" \
        "Enable auto-start on boot" \
        "- 设置开机自启"
    
    printf "  \033[34mdisable\033[0m     - %-40s %s\n" \
        "Disable auto-start on boot" \
        "- 取消开机自启"
    
    printf "  \033[34mlogs\033[0m        - %-40s %s\n" \
        "View output logs (Ctrl+C to exit)" \
        "- 查看输出日志（按Ctrl+C退出）"
    
    printf "  \033[34mlogs error\033[0m  - %-40s %s\n" \
        "View error logs (Ctrl+C to exit)" \
        "- 查看错误日志（按Ctrl+C退出）"
    
    printf "  \033[34muninstall\033[0m   - %-40s %s\n" \
        "Uninstall service" \
        "- 卸载服务"
    
    printf "  \033[34mhelp\033[0m        - %-40s %s\n" \
        "Show help information" \
        "- 显示帮助信息"
}


main() {
    # 检查是否以root权限运行
    if [ "$(id -u)" -ne 0 ]; then
        echo "Error: Please run with root privileges（sudo）"
        exit 1
    fi

    if [ $# -eq 0 ]; then
        show_gm_help
        exit 1
    fi

    case "$1" in
        install)
            Install_GM
            ;;
        start)
            start_gm_service
            ;;
        setport)
            Set_Server_Port "$2"
            ;;
        port)
            Check_Server_Port
            ;;
        stop)
            stop_gm_service
            ;;
        restart)
            restart_gm_service
            ;;
        status)
            status_gm_service
            ;;
        enable)
            enable_gm_service
            ;;
        disable)
            disable_gm_service
            ;;
        logs)
            view_gm_logs "$2"
            ;;
        uninstall)
            Uninstall_GM
            ;;
        help)
            show_gm_help
            ;;
        *)
            echo "Unknown command: $1"
            show_gm_help
            exit 1
            ;;
    esac
}
# ########################################################################
# 执行
# ########################################################################
main "$@"

# install_build_deps